package com.example.block_chain.controller.major;

import com.example.block_chain.RabbitMQ.Producer;
import com.example.block_chain.common.AppHttpCodeEnum;
import com.example.block_chain.common.ResponseResult;
import com.example.block_chain.common.SystemParameters;
import com.example.block_chain.domain.dto.MajorDto;
import com.example.block_chain.domain.pbft.VoteInfo;
import com.example.block_chain.domain.pojo.Admin;
import com.example.block_chain.domain.pojo.Major;
import com.example.block_chain.service.blockChain.BlockService;
import com.example.block_chain.service.faculty.FacultyService;
import com.example.block_chain.service.major.MajorService;
import com.example.block_chain.utils.KeyValueReaderUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/*
 *@description: 专业相关接口
 *@author: hisen
 *@Time: 2024/3/4  17:52
 */
@RestController
public class MajorController {

    @Resource
    MajorService majorService;

    @Resource
    BlockService blockService;

    @Resource
    FacultyService facultyService;

    @Resource
    Producer producer;

    @GetMapping("/getMajor")
    public ResponseResult getMajor(@RequestParam String schoolCode, @RequestParam String facultyCode, HttpSession session) {
        if (session.getAttribute("admin") == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        List<Major> majors = majorService.getMajor(schoolCode, facultyCode);
        return ResponseResult.okResult(majors);
    }

    @PostMapping("/addMajor")
    public ResponseResult addMajor(@RequestBody MajorDto dto, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        if (!Objects.equals(admin.getAuthority(), SystemParameters.AUTHORITY_0.toString())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AUTHORITY_DEFICIENCY);
        }
        Major major = new Major();
        BeanUtils.copyProperties(dto, major);
        //学校是否存在
        if (KeyValueReaderUtil.getDigestByCode(dto.getSchoolCode(), SystemParameters.SCHOOL_FILE_PATH) == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SCHOOL_NO_EXISTS);
        }
        //学院是否存在
        if (facultyService.getFaculty(major.getFacultyCode()) == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FACULTY_NO_EXISTS);
        }
        //专业上链
        if (majorService.getMajor(major.getMajorCode()) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CODE_EXISTS);
        }
        majorService.save(major);

        VoteInfo voteInfo = blockService.createMajorBlock(major.getFacultyCode(), major.getMajorCode());
        producer.sendMessage(voteInfo);

        return ResponseResult.okResult();
    }
}
